﻿using System;
using System.Text;

using ET;
using Marx;

namespace Demo
{
    public abstract class ServiceBase : Entity, IAwake
    {
        private CoroutineLockComponent lock_;

        public async ETTask StartService()
        {
            lock_ = CoroutineLockComponent.Instance;
            AddComponent<MailBoxComponent>();
            await this.AddLocation();

            await OnStartAsync();
        }

        protected virtual async ETTask OnStartAsync()
        {
            await ETTask.CompletedTask;
        }

        public ETTask StopService()
        {
            return OnStopAsync();
        }

        protected virtual async ETTask OnStopAsync()
        {
            await ETTask.CompletedTask;
        }

        public void Init()
        {
            OnInit();
        }

        protected virtual void OnInit()
        {

        }

        protected async ETTask<T> LockAction<T>(long id, Func<ETTask<T>> func)
        {
            try
            {
                using (await lock_.Wait((int)Id, id))
                {
                    return await func();
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw e;
            }
        }

        protected async ETTask LockAction(long id, Func<ETTask> func)
        {
            try
            {
                using (await lock_.Wait((int)Id, id))
                {
                    await func();
                }
            }
            catch (Exception e)
            {
                Log.Error(e);
                throw e;
            }
        }
    }
}
